package com.wyait.manage.idempotent.token;


import com.wyait.manage.idempotent.enums.TokenType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Package: com.wyait.manage.idempotent.token
 * Description：防重复提交token管理器
 * Author: huangjian
 * Date:  2020/9/13 18:21
 * Modified By:
 *
 * @author huangjian
 */

@Component
public class TokenManager {
    @Resource
    private List<TokenService> tokenServiceList;

    private volatile static TokenService tokenService;

    @Value("${app.idempotent.token.type}")
    private String tokenTypeCode;

    private TokenService chooseOne() {
        TokenType tokenType = TokenType.valueOf(tokenTypeCode);
        if (Objects.isNull(tokenType)) {
            throw new IllegalArgumentException("系统token存储配置出错，请检查");
        }
        Optional<TokenService> first = tokenServiceList.stream().filter(item -> tokenType.equals(item.support())).findFirst();
        if (first.isPresent()) {
            return first.get();
        }
        throw new IllegalArgumentException("系统token存储配置不支持");
    }

    public  TokenService newInstance() {
        if (tokenService == null) {
            synchronized (TokenService.class) {
                if (tokenService == null) {
                    tokenService = chooseOne();
                }
            }
        }
        return tokenService;
    }

    public String getToken() {
        return newInstance().getToken();
    }

    public boolean verifyToken(String token) {
        return newInstance().verifyToken(token);
    }
}
